#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import time
from resource_management import *


class Master(Script):

    def install(self, env):
        import params
        print('Starting Install the Master of PGSQL ')
        #安装
        version=params.pgsql_version
        data_dir=params.pgsql_data_dir
        Execute("yum remove postgresql* -y")
        # 安装客户端、服务端
        Execute('yum install postgresql{} -y'.format(version))
        Execute("yum install postgresql"+version+"-server -y")
        Execute ("rm -rf {} ".format(data_dir))
        # 配置PGDATA
        Execute("sed -i 's!^Environment=PGDATA.*!Environment=PGDATA={}!' /usr/lib/systemd/system/postgresql-{}.service".format(data_dir,version))
        Execute("systemctl daemon-reload")
        Execute("/usr/pgsql-"+version+ "/bin/postgresql-"+version+"-setup initdb")
        Execute("systemctl enable postgresql-"+version)
        print('Finish install the MASTER of PGSQL')
        db_username=params.pgsql_db_username
        db_password=params.pgsql_db_password

        # 进行配置
        self.staticConfigure(env)
       
        # 启动
        Execute("systemctl start postgresql-{}".format(version))
        
        repuser_username=params.pgsql_db_repuser_username
        repuser_password=params.pgsql_db_repuser_password
        service_packagedir = params.service_packagedir
        create_repuser_script = "{}/files/create_repuser.sh".format(service_packagedir)
        create_user_script = "{}/files/create_user.sh".format(service_packagedir)
        #去掉windows下的空白字符，不然脚本无法执行
        Execute(" sed -i 's/\\r$//' {}/files/*.sh".format(service_packagedir))

        #如果数据库初始化用户不是postgres，则进行创建
        if db_username != 'postgres':
            Execute('su root -c " sh {} {} {}"'.format(create_user_script, db_username, db_password))
        #创建复制用户
        Execute('su root -c "sh {} {} {}" '.format(create_repuser_script, repuser_username, repuser_password))
        # 更新密码
        self.updatePassword(env)

    # 进行文件配置
    def staticConfigure(self,env):
        import params
        env.set_params(params)
        postgresql_conf = InlineTemplate(params.pgsql_conf_content)
        data_dir = params.pgsql_data_dir
        File("{}/postgresql.conf".format(data_dir), content=postgresql_conf, owner='postgres')
        pg_hba_conf = InlineTemplate(params.pgsql_hba_content)
        File("{}/pg_hba.conf".format(data_dir), content=pg_hba_conf, owner='postgres')

    def updatePassword(self,env):
        import params
        service_packagedir = params.service_packagedir
        update_pwd_path = "{}/files/update_pwd.sh".format(service_packagedir)
        pg_port = params.pgsql_server_port
        db_username = params.pgsql_db_username
        db_password = params.pgsql_db_password
        Execute('su root -c "sh {} {} {}" '.format(update_pwd_path, db_username, db_password))
        repuser_username = params.pgsql_db_repuser_username
        repuser_password = params.pgsql_db_repuser_password
        Execute('su root -c "sh {} {} {}"'.format(update_pwd_path, repuser_username, repuser_password))


    def configure(self, env ):
        print("Configure the Master of PGSQL")
        self.staticConfigure(env)
        self.updatePassword(env)



    def stop(self, env):
        import params
        version = params.pgsql_version
        print('Stop the Master of PGSQL')
        Execute("systemctl stop postgresql-{}".format(version))

    def start(self, env):
        import params
        version = params.pgsql_version
        print('Start the Master of PGSQL')
        self.staticConfigure(env) # FOR SECURITY
        Execute("systemctl start postgresql-{}".format(version))
        self.updatePassword(env)  # FOR SECURITY


    def status(self, env):
        import params
        print('Status of the PGSQL Master')
        # pid_file="{}/{}".format(params.pgsql_pid_dir,params.pgsql_pid)
        version = params.pgsql_version
        try:
            Execute("systemctl status postgresql-{}".format(version))
        except:
            print('PGSQL MASTER IS NOT RUNNING')
            raise ComponentIsNotRunning()


if __name__ == "__main__":
    Master().execute()